package com.zxy.controlcenter.core.aop;

import com.zxy.controlcenter.core.exception.ServiceException;
import com.zxy.controlcenter.core.http.HttpContext;
import com.zxy.controlcenter.core.log.LogManager;
import com.zxy.controlcenter.core.log.factory.LogTaskFactory;
import com.zxy.controlcenter.core.message.response.ErrorResponseData;
import com.zxy.controlcenter.core.shiro.ShiroKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.Objects;

/**
 * 全局异常拦截器
 *
 * @author zxy
 */
@Slf4j
@ControllerAdvice
@Order(-1)
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorResponseData bussiness(ServiceException e) {
        LogManager.me().executeLog(LogTaskFactory.exceptionLog(Objects.requireNonNull(ShiroKit.getUser()).getId(), e));
        Objects.requireNonNull(HttpContext.getRequest()).setAttribute("tip", e.getMessage());
        log.error("业务异常:", e);
        return new ErrorResponseData(e.getCode(), e.getMessage());
    }
}
